package com.spring.theory.bean.lifeCycle;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 阅读 2-1 bean的生命周期 - 实例化、依赖注入、初始化、销毁
 *
 * @author 24373
 * @date 2023/12/23 22:50
 */
@Component
@Slf4j
public class LifeCycleBean implements InitializingBean, DisposableBean, BeanNameAware, ApplicationContextAware {

    public LifeCycleBean() {
        log.info("LifeCycleBean--bean构造器");
    }

    /**
     * 字符串一般不会自动注入；需要搭配注解使用
     */
    @Autowired
    public void autoWire(@Value("${server.port}") String port) {
        log.info("LifeCycleBean--依赖注入:{}", port);
    }

    @Override
    public void setBeanName(String name) {
        log.info("LifeCycleBean--aware接口BeanNameAware bean初始化前");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("LifeCycleBean--aware接口ApplicationContextAware bean初始化前" + applicationContext);
    }

    /**
     * 初始化方法
     */
    @PostConstruct
    public void init() {
        log.info("LifeCycleBean--@PostConstruct注解 bean初始化");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("LifeCycleBean--spring内置初始化 LifeCycleBean init");
    }

    @PreDestroy
    public void destroy2() {
        log.info("LifeCycleBean--@PreDestroy注解 bean销毁");
    }

    @Override
    public void destroy() throws Exception {
        log.info("LifeCycleBean--spring内置销毁 LifeCycleBean destroy");
    }

}
